﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
namespace PasteTimer.taskmodels
{
    /// <summary>
    /// 
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
    public class TaskBindUserAppService : IUserAppService
    {

        private readonly IPasteTimerDbContext _dbContext;

        private ModelHelper _modelHelper => LazyServiceProvider.LazyGetRequiredService<ModelHelper>();

        public TaskBindUserAppService(IPasteTimerDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 按页获取
        ///</summary>
        /// <param name="page">页码</param>
        /// <param name="size">页大小</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<TaskBindUserListDto>> GetListAsync(int page = 1, int size = 20)
        {
            var _userid = base.ReadCurrentAdminId();
            var querytask = _modelHelper.QueryableMyTaskId(_dbContext, _userid);
            var query = _dbContext.TaskBindUser.Where(t => querytask.Contains(t.TaskId)).OrderByDescending(xy => xy.Id);
            var _pagedto = new PagedResultDto<TaskBindUserListDto>();
            if (page == 1)
            {
                _pagedto.TotalCount = await query.CountAsync();
            }
            var userList = await query.Page(page, size).ToListAsync();
            var temList = ObjectMapper.Map<List<TaskBindUser>, List<TaskBindUserListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }

        /// <summary>
        /// 根据ID获取单项
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public TaskBindUserDto GetByIdAsync(int id)
        {
            var _userid = base.ReadCurrentAdminId();
            var info = _dbContext.TaskBindUser.Where(t => t.Id == id).AsNoTracking().FirstOrDefault();
            if (info == null || info == default)
            {
                throw new PasteTimerException("没有找到这样的信息", 404);
            }
            _modelHelper.HasTaskException(_dbContext, _userid, info.TaskId);
            var temList = ObjectMapper.Map<TaskBindUser, TaskBindUserDto>(info);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public TaskBindUserUpdateDto GetInfoForUpdateAsync(int id)
        {
            var _userid = base.ReadCurrentAdminId();
            var info = _dbContext.TaskBindUser.Where(t => t.Id == id).AsNoTracking().FirstOrDefault();
            if (info == null || info == default)
            {
                throw new PasteTimerException("没有找到这样的信息", 404);
            }
            _modelHelper.HasTaskException(_dbContext, _userid, info.TaskId);
            var temList = ObjectMapper.Map<TaskBindUser, TaskBindUserUpdateDto>(info);
            return temList;
        }

        /// <summary>
        /// 添加一个
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "bind" })]
        public async Task<TaskBindUserDto> CreateItemAsync(TaskBindUserAddDto input)
        {
            var _find = _dbContext.TaskBindUser.Where(x => x.UserId == input.UserId && x.TaskId == input.TaskId).Select(x => x.Id).FirstOrDefault();
            if (_find != 0)
            {
                throw new PasteTimerException("已经存在这样的关系数据了，无法重复写入！");
            }
            var _userid = base.ReadCurrentAdminId();
            _modelHelper.HasTaskException(_dbContext, _userid, input.TaskId);
            var info = ObjectMapper.Map<TaskBindUserAddDto, TaskBindUser>(input);
            info.CreateDate = DateTime.Now;            //添加自定义
            info.Create_UserId = base.ReadCurrentAdminId();
            _dbContext.Add(info);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<TaskBindUser, TaskBindUserDto>(info);
            return backinfo;
        }

        /// <summary>
        /// 更新一个
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "bind" })]
        public async Task<TaskBindUserDto> UpdateItemAsync(TaskBindUserUpdateDto input)
        {
            var _find = _dbContext.TaskBindUser.Where(x => x.UserId == input.UserId && x.TaskId == input.TaskId && x.Id != input.Id).Select(x => x.Id).FirstOrDefault();
            if (_find != 0)
            {
                throw new PasteTimerException("已经存在这样的关系数据了，无法重复写入！");
            }
            var info = await _dbContext.TaskBindUser.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }
            var _userid = base.ReadCurrentAdminId();
            _modelHelper.HasTaskException(_dbContext, _userid, info.TaskId);
            ObjectMapper.Map<TaskBindUserUpdateDto, TaskBindUser>(input, info);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<TaskBindUser, TaskBindUserDto>(info);
            return backinfo;
        }

        /// <summary>
        /// 删除一个关系绑定
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> Delete(int id)
        {
            var _userid = base.ReadCurrentAdminId();
            var info = await _dbContext.TaskBindUser.Where(t => t.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new PasteTimerException("没有找到这样的信息", 404);
            }
            _modelHelper.HasTaskException(_dbContext, _userid, info.TaskId);
            _dbContext.Remove(info);
            await _dbContext.SaveChangesAsync();
            return "删除成功!";
        }
    }
}
